<?php

class FormLogin extends CFormModel {

    public $email;
    public $password;
    public $rememberMe;

    public $config = array();

    public function init() {
        $this->config = array(
            'class' => 'form',
            'elements' => array(
                'email' => array('type' => 'text'),
                'password' => array('type' => 'password'),
                'rememberMe' => array('type' => 'checkbox', 'layout' => "<br/>{input} {label}\n{hint}\n{error}")
            ),
            'buttons' => array(
                'login' => array('type' => 'htmlSubmit', 'value' => 1, 'class' => 'blue', 'label' => '<span class="label">Войти</span>'),
                'recover' => array('type' => 'link', "class" => "right_alight", 'label' => 'Забыли пароль?', 'href' => Y::url("user/recover")),
                'registration' => array('type' => 'link', "class" => "right_alight", 'label' => 'Регистрация', 'href' => Y::url("user/registration")),
            )
        );
        return parent::init();
    }

    public function rules() {
        return array(
            array('email, password', 'required'),
            array('password', 'authenticate'),
            array('rememberMe', 'safe'),
        );
    }

    public function attributeLabels() {
        return array(
            'rememberMe' => 'Запомнить?',
            'email' => 'E-mail',
            'password' => 'Пароль',
        );
    }

    public function authenticate($attribute, $params) {
        if(!$this->hasErrors()) {
            $identity = new UserIdentity($this->email, $this->password);
            $identity->authenticate();
            switch($identity->errorCode) {
                case UserIdentity::ERROR_NONE:
                    $duration = $this->rememberMe ? 3600 * 24 * 30 : 0;
                    Yii::app()->user->login($identity, $duration);
                    Yii::app()->request->redirect(Yii::app()->user->returnUrl);
                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError('email', 'Пароль и логин не верны');
                    break;
                case UserIdentity::ERROR_STATUS_BANNED:
                    $this->addError('email', 'А вас забанили =).');
                    break;
                case UserIdentity::ERROR_STATUS_NOTACTIVE:
                    $this->addError('email', 'Подтвердите свой E-mail.');
                    break;
                default:
                    $this->addError('email', 'Пароль и логин не верны');
                    break;
            }
        }
    }
}
